package com.qna.web;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qna.DummyDB;
import com.qna.pojo.Question;

@Controller
public class QuestionController {

	@RequestMapping("/emailform")
	public ModelAndView emailForm() {

		String message = "emailform";
		System.out.println(message);
		return new ModelAndView("emailform", "message", message);
	}

	private static DummyDB dummyDB = new DummyDB();

	@RequestMapping(value = "/submitq", method = RequestMethod.GET)
	public ModelAndView submitq(Model model, HttpServletRequest request) {
		Question userForm = null;
		if(request.getParameter("filename") != null){
			String desktop = System.getProperty ("user.home") + "/Desktop/yo/";
			File file = new File(desktop+"/"+request.getParameter("filename"));
			userForm = new Question();
			try {

				JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
				Unmarshaller u = jaxbContext.createUnmarshaller();
				userForm = (Question)u.unmarshal(file);
			} 
			catch (JAXBException e) {
				e.printStackTrace();
			} 
		}
		else{
			userForm = new Question();
		}
		return new ModelAndView("submitq", "userForm", userForm);
	}

	@RequestMapping(value = "/get_related_product_list", 
			method = RequestMethod.GET, 
			headers="Accept=*/*")
	public @ResponseBody List<String> getRelatedProductList(@RequestParam("term") String query) {
		List<String> countryList = dummyDB.getRelatedProductList(query);

		return countryList;
	}

	@RequestMapping(value = "/get_related_to_topic_list", 
			method = RequestMethod.GET, 
			headers="Accept=*/*")
	public @ResponseBody List<String> getRelatedToTopicList(@RequestParam("term") String query) {
		List<String> countryList = dummyDB.getRelatedToTopicList(query);

		return countryList;
	}
}